package demo2;
import java.util.Arrays;
import java.util.Comparator;
//接口使用实例

//定义学生类
class Student  implements Comparable<Student>{
    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }
    String name;
    int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    //创建一个自己的排序方式
    public void  sort(Comparable[] comparables) {
        for(int i = 0; i < comparables.length-1; i++) {
            for(int j = 0; j < comparables.length-1-i; j++) {
                if(comparables[j].compareTo(comparables[j+1])>0) {
                    Comparable tmp = comparables[j];
                    comparables[j] = comparables[j+1];
                    comparables[j+1] = tmp;
                }
            }
        }
    }
}

public class TestOne {

    public static void main(String[] args) {
        Student student1 = new Student("zhangsan", 18);
        Student student2 = new Student("lisi", 17);
        Student student3 = new Student("wangwu", 19);

        //对象数组
        Student[] studentArray = {student1, student2, student3};

        NameComparator ncpt = new NameComparator();
        System.out.println("排序前"+Arrays.toString(studentArray));
        //其实这样写就有点怪异了 应当将sort函数写到TestOne中
        student1.sort(studentArray);
        System.out.println("排序后"+Arrays.toString(studentArray));

    }
}

//        //Arrays.sort(studentArray);
//        System.out.println("排序前"+Arrays.toString(studentArray));
//
//        Arrays.sort(studentArray);
//
//        System.out.println("排序后"+Arrays.toString(studentArray));
//    }
//}
//创建比较器
//根据姓名比较
class NameComparator implements Comparator<Student>{
    @Override
    public int compare(Student one,Student two) {
        return one.name.compareTo(two.name);
    }
}
//根据年龄比较
class AgeComparator implements Comparator<Student>{
    @Override
    public int compare(Student one,Student two) {
        return one.age-two.age;
    }
}